package com.mine;

public class MyParseInt {
    public static int myParseInt(String s) {
        if (s == null || s.length() == 0) {
            throw new RuntimeException("传输字符串为空");
        }
        if (s.charAt(0) == '0') {
            throw new RuntimeException("首字母不能为0");
        }
        if (s.charAt(0) == '-' && s.length() == 1) {
            throw new RuntimeException("不能只有一个负号");
        }
        boolean neg;
        int limit;
        int index = 0;
        if (s.charAt(0) == '-') {
            neg = true;
            limit = Integer.MIN_VALUE;
            index++;
        } else {
            neg = false;
            limit = -Integer.MAX_VALUE;
        }
        int res = 0;
        int tmp = limit / 10;
        for (int i = index; i < s.length(); i++) {
            if (res < tmp) {
                throw new RuntimeException("越界");
            }
            res = res * 10;
            int digit = digit(s.charAt(i));
            if (res < limit + digit) {
                throw new RuntimeException("越界");
            }
            res -= digit;
        }
        if (!neg) {
            res = -res;
        }
        return res;
    }

    public static int digit(char c) {
        if (c > '9' || c < '0') {
            throw new RuntimeException("字符有错误");
        }
        return c - '0';
    }

    public static void main(String[] args) {
        System.out.println(myParseInt("-2147483648"));
    }
}
